package Dao;

import java.sql.*;

public class baseDao {	
	private String driver = "com.mysql.jdbc.Driver";
	private String url = "jdbc:mysql://localhost/data";
	private String user = "root";
	private String password = "root";
	
	Connection conn = null;
	ResultSet result;
	Statement state;
	
	public baseDao(String driver,String url,String user,String password){
		this.driver = driver;
		this.url = url;
		this.user = user;
		this.password = password;
	}
	
	public Connection getConnection(){		
			try {
				Class.forName(driver);
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}			
			try {
				conn = DriverManager.getConnection(url,user,password);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return conn;		
	}
	
	public void closeConn(){
		if(result!=null){
			try {
				result.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if(conn!=null){
			try{
				conn.close();
			}catch(SQLException e){
				e.printStackTrace();
			}
		}
		if(state!=null){
			try {
				state.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	//更新，返回成功条数
	public int executeUpdate(String sql){
		Statement stmt;
		try {
			stmt = this.conn.createStatement();
			return stmt.executeUpdate(sql);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
		return 0;
	}

	public int basicUpdate(String sql,Object...params){
		PreparedStatement prep = null;
		try {
			prep = conn.prepareStatement(sql);
			for(int i=0; i<params.length; i++){
				prep.setObject(i+1, params[i]);
			}
		return prep.executeUpdate();
		
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
		return 0;
	}
	
	//查询，返回结果集
	public ResultSet executeQuery(String sql,Object...params){
		PreparedStatement prep = null;
		
		try {
			prep = conn.prepareStatement(sql);
			for(int i=0; i<params.length; i++){
				prep.setObject(i+1, params[i]);
			}
			return prep.executeQuery();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
		return null;
	}

}
